﻿using System.IO;
using System.Web.Script.Serialization;
using Newtonsoft.Json;

namespace TestWcfRestService
{
    public static class JsonHelper
    {
        public static string ToJson(this object obj)
        {
            var serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }

        public static T FromJson<T>(this string jsonString)
        {
            if (string.IsNullOrWhiteSpace(jsonString))
                return default(T);

            var deserializer = new JavaScriptSerializer();
            return deserializer.Deserialize<T>(jsonString);
        }

        public static string ToJsonByNewton(this object obj)
        {
            var serializer = new JsonSerializer();
            using (var sw = new StringWriter())
            {
                serializer.Serialize(sw, obj);
                sw.Flush();
                return sw.ToString();
            }
        }

        public static T FromJsonByNewton<T>(string jsonString)
        {
            if (string.IsNullOrWhiteSpace(jsonString))
                return default(T);

            var serializer = new JsonSerializer();
            using (var sr = new StringReader(jsonString))
            {
                var reader = new JsonTextReader(sr);
                return serializer.Deserialize<T>(reader);
            }
        }

        public static object FromJsonByNewton(string jsonString)
        {
            if (string.IsNullOrWhiteSpace(jsonString))
                return null;

            var serializer = new JsonSerializer();
            using (var sr = new StringReader(jsonString))
            {
                var reader = new JsonTextReader(sr);
                return serializer.Deserialize(reader);
            }
        }

        public static string ToFormattedJson(this object obj)
        {
            var json = obj.ToJson();
            return FormatJson(json);
        }

        public static string FormatJson(string jsonString)
        {
            var jsonObject = FromJsonByNewton(jsonString);
            if (null == jsonObject)
                return null;

            var serializer = new JsonSerializer();
            using (var sw = new StringWriter())
            {
                var writer = new JsonTextWriter(sw);
                writer.Formatting = Formatting.Indented;
                writer.Indentation = 4;
                writer.IndentChar = ' ';
                serializer.Serialize(writer, jsonObject);
                return sw.ToString();
            }
        }
    }
}
